<template>
  <div class="box">
      <header class="header">
        <van-search shape="round" v-model="searchText" placeholder="请输入搜索关键词" show-action>
          <template #left>
            <div class="searchback" @click="$router.back()">
              <van-icon name="arrow-left" size="20"/>
            </div>
          </template>
          <template #action>
            <div @click="onSearch">搜索</div>
          </template>
        </van-search>
      </header>
      <section class="content">
        <div class="searchBox">
          <h5>搜索历史</h5>
          <van-tag plain size="medium" v-for="(item, index) of historylist" :key="index" @click="search(item)">{{ item }}</van-tag>
          <h5>热门搜索</h5>
          <van-tag plain size="medium" v-for="(item, index) of hotSearchlist" :key="index" @click="search(item)">{{ item }}</van-tag>
        </div>
      </section>
    </div>
</template>

<script>
import Vue from 'vue'
import { Search, Icon, Dialog, Tag, Toast } from 'vant'

Vue.use(Search)
Vue.use(Icon)
Vue.use(Dialog)
Vue.use(Tag)
Vue.use(Toast)

export default {
  data () {
    return {
      searchText: '',
      historylist: [],
      hotSearchlist: ['手机', '电脑', '零食', '美妆', '数码配件', '服装', '男装', '女装', '背包', '眼镜', '耳环']
    }
  },
  methods: {
    onSearch () {
      if (this.searchText.trim() === '') { // trim() 方法用于删除字符串的头尾空格。trim() 方法不会改变原始字符串。
        Toast('请先输入需要搜索的关键词')
        return
      }
      // 从本地获取 搜索列表的数据
      const searchListStr = localStorage.getItem('searchlist') || '[]'
      const searchList = JSON.parse(searchListStr)
      // 获取本次输入的查询的信息在素组中是否存在
      const index = searchList.indexOf(this.searchText)
      // console.log(index)
      if (index === -1) {
        searchList.unshift(this.searchText)
      } else {
        // 删除原来的位置，在数组的头部插入
        searchList.splice(index, 1)
        searchList.unshift(this.searchText)
      }
      this.historylist = searchList
      localStorage.setItem('searchlist', JSON.stringify(searchList))
      this.$router.replace('/searchlist?searchText=' + this.searchText)
    },
    search (val) {
      this.searchText = val
      this.onSearch()
    }
  },
  mounted () {
    const searchListStr = localStorage.getItem('searchlist')
    const searchList = JSON.parse(searchListStr)
    this.historylist = searchList
  }
}
</script>

<style lang="scss" scoped>
.header {
  border-bottom: 1px solid #ddd;
  margin-bottom: 10px;
  .van-search {
    padding: 5px 12px;
  }
  .van-search__action {
    background: red;
    margin-left: 5px;
    border-radius: 8px;
    font-size: 12px;
    line-height: 30px;
  }
  .searchback {
    margin: 0 20px 0 0;
  }
  .van-search__content van-search__content--square {
    border-radius: 20px;
  }
}
.searchBox {
  padding-left: 15px;
  background: #fff;
  .van-tag {
    margin: 5px 5px;
    background-color: #eee;
  }
  .van-tag--plain::before {
    border: none;
  }
  h5 {
    padding: 10px 0;
  }
}
</style>
